package com.zz.inventory.controller;

import java.util.*;
import java.io.IOException;

import com.ruoyi.common.security.utils.SecurityUtils;
import com.zz.inventory.domain.CouponUsage;
import com.zz.inventory.service.ICouponUsageService;
import jakarta.servlet.http.HttpServletResponse;
import org.example.dto.CouponUsageDTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.zz.inventory.domain.Coupons;
import com.zz.inventory.service.ICouponsService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 优惠券管理Controller
 * 
 * @author zz
 * @date 2025-07-07
 */
@RestController
@RequestMapping("/coupons")
public class CouponsController extends BaseController
{
    @Autowired
    private ICouponsService couponsService;

    @Autowired
    private ICouponUsageService couponUsageService;

    /**
     * 激活优惠卷
     * @param coupons
     * @return
     */
    @PostMapping("/activate")
    public AjaxResult activateCoupon(@RequestBody Coupons coupons) {
        Long userId = SecurityUtils.getUserId();

        // 验证优惠券是否存在
        Coupons coupon = couponsService.selectCouponsByCouponId(coupons.getCouponId());
        if (coupon == null) {
            return AjaxResult.error("优惠券不存在");
        }

        // 检查是否已领取
        CouponUsage usage = new CouponUsage();
        usage.setUserId(userId);
        usage.setSchoolId(coupons.getSchoolId());
        List<CouponUsage> list = couponUsageService.selectCouponUsageList(usage);
        if (!list.isEmpty()) {
            return AjaxResult.error("您已领取过该校的优惠券");
        }

        // 创建使用记录
        CouponUsage newUsage = new CouponUsage();
        newUsage.setCouponId(coupons.getCouponId());
        newUsage.setUserId(userId);
        newUsage.setSchoolId(coupons.getSchoolId());
        newUsage.setReceiveTime(new Date());
        newUsage.setActivateTime(new Date());
        newUsage.setStatus(1);

        // 设置过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, coupon.getValidPeriod());
        newUsage.setExpireTime(calendar.getTime());

        return toAjax(couponUsageService.insertCouponUsage(newUsage));
    }

    /**
     * 检查是否已领取优惠卷
     * @param schoolId
     * @return
     */
    @GetMapping("/check")
    public AjaxResult checkCouponReceived(@RequestParam Long schoolId) {
        Long userId = SecurityUtils.getUserId();

        CouponUsage usage = new CouponUsage();
        usage.setUserId(userId);
        usage.setSchoolId(schoolId);
        List<CouponUsage> list = couponUsageService.selectCouponUsageList(usage);

        Map<String, Object> result = new HashMap<>();
        result.put("hasReceived", !list.isEmpty());
        return AjaxResult.success(result);
    }

    /**
     * 被老师模块调用通过用户ID查找优惠卷
     * 检查优惠卷记录中是否包含此ID
     *
     */
    @PostMapping("/records/jianCha")
    AjaxResult getStudentExamRecords(@RequestBody CouponUsageDTo couponUsageDTo){
     Long userid =  couponUsageDTo.getUserId();
        System.out.println("！！！！！！！！！！！调用成功");
        CouponUsage couponUsage = couponUsageService.selectCouponUsageByUserId(userid);
        //1,通过ID查找优惠卷数据
       if (couponUsage != null){
           return AjaxResult.success("优惠卷已领取");
       }
        return AjaxResult.success("优惠卷未领取");
    }



    /**
     * 查询优惠券管理列表
     */
    @RequiresPermissions("platform:coupons:list")
    @GetMapping("/list")
    public TableDataInfo list(Coupons coupons)
    {
        startPage();
        List<Coupons> list = couponsService.selectCouponsList(coupons);
        return getDataTable(list);
    }

    /**
     * 导出优惠券管理列表
     */
    @RequiresPermissions("platform:coupons:export")
    @Log(title = "优惠券管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Coupons coupons)
    {
        List<Coupons> list = couponsService.selectCouponsList(coupons);
        ExcelUtil<Coupons> util = new ExcelUtil<Coupons>(Coupons.class);
        util.exportExcel(response, list, "优惠券管理数据");
    }

    /**
     * 获取优惠券管理详细信息
     */
    @RequiresPermissions("platform:coupons:query")
    @GetMapping(value = "/{couponId}")
    public AjaxResult getInfo(@PathVariable("couponId") Long couponId)
    {
        return success(couponsService.selectCouponsByCouponId(couponId));
    }

    /**
     * 新增优惠券管理
     */
    @RequiresPermissions("platform:coupons:add")
    @Log(title = "优惠券管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Coupons coupons)
    {
        return toAjax(couponsService.insertCoupons(coupons));
    }

    /**
     * 修改优惠券管理
     */
    @RequiresPermissions("platform:coupons:edit")
    @Log(title = "优惠券管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Coupons coupons)
    {
        return toAjax(couponsService.updateCoupons(coupons));
    }

    /**
     * 删除优惠券管理
     */
    @RequiresPermissions("platform:coupons:remove")
    @Log(title = "优惠券管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{couponIds}")
    public AjaxResult remove(@PathVariable Long[] couponIds)
    {
        return toAjax(couponsService.deleteCouponsByCouponIds(couponIds));
    }
}
